package com.lky.marshall.mallcart.interceptor;

import com.lky.common.constant.AuthServerConstant;
import com.lky.common.constant.CartConstant;
import com.lky.common.vo.MemberVo;
import com.lky.marshall.mallcart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by
 * autor : Marshall lky
 * datetime: 2021/6/1 11:06
 * 执行目标方法之前，判断用户的登录状态，并封装给controller
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 在目标方法执行之前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserInfoTo userInfo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberVo member = (MemberVo) session.getAttribute(AuthServerConstant.SESSION_NAME);
        if (member != null) {
            //登陆
            userInfo.setUserId(member.getId());

        }
//        userInfo.setUserId(member.getId());
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(name)){
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setCheck(true);
                }
            }
        }
        //如果没有临时用户需要分配一个临时用户
        if (StringUtils.isBlank(userInfo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfo.setUserKey(uuid);
        }
        //目标方法执行之前
        threadLocal.set(userInfo);

        return true;
    }

    /**
     * 业务执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.getCheck()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("marshallmall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
